package com.maben.easyui.config;

import com.alibaba.druid.pool.DruidDataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;

@Configuration
@MapperScan(basePackages = DataSource1Config.PACKAGE_MAPPER,sqlSessionFactoryRef = "datasource1SqlSessionFactory")
public class DataSource1Config {
    static final String PACKAGE_MAPPER = "com.maben.easyui.mapper";
    static final String MAPPER_LOCATION = "classpath:com/maben/easyui/mapper/*.xml";
    static final String PACKAGE_POJO = "com.maben.easyui.pojo,com.maben.easyui.controller.vo";

    @Value("${dataSource1.driverClassName}")
    private String driverClassName;
    @Value("${dataSource1.url}")
    private String url;
    @Value("${dataSource1.username}")
    private String username;
    @Value("${dataSource1.password}")
    private String password;
    @Bean(name = "datasource1DataSource")
    public DataSource datasource1DataSource() {
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setDriverClassName(driverClassName);
        dataSource.setUrl(url);
        dataSource.setUsername(username);
        dataSource.setPassword(password);
        return dataSource;
    }

    @Bean(name = "datasource1TransactionManager")
    public DataSourceTransactionManager datasource1TransactionManager() {
        return new DataSourceTransactionManager(datasource1DataSource());
    }

    @Bean(name = "datasource1SqlSessionFactory")
    public SqlSessionFactory datasource1SqlSessionFactory(@Qualifier("datasource1DataSource") DataSource datasource1DataSource)
            throws Exception {
        final SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
        sessionFactory.setDataSource(datasource1DataSource);
        sessionFactory.setMapperLocations(new PathMatchingResourcePatternResolver()
                .getResources(DataSource1Config.MAPPER_LOCATION));
        sessionFactory.setTypeAliasesPackage(DataSource1Config.PACKAGE_POJO);
        //驼峰处理
//        final org.apache.ibatis.session.Configuration ibatisConfiguration = new org.apache.ibatis.session.Configuration();
//        ibatisConfiguration.setMapUnderscoreToCamelCase(true);
//        sessionFactory.setConfiguration(ibatisConfiguration);
        return sessionFactory.getObject();
    }

}
